package controllers

import (
	"chapter6/common"
	"chapter6/models"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
)

/**
 * Created with Goland.
 * User: 令狐飞侠
 * Date: 2022-3-8
 * Description: orm
 */

type UerController struct {
	beego.Controller
}


//用户列表
func (c *UerController)ListUser() {
	fmt.Println("ListUser")
	var userList []*models.User
	//c.GetString()
	//1 orm对象
	o := orm.NewOrm()
	qs := o.QueryTable(common.TbUser)

	//2 查询前30条记录
	count, err := qs.Limit(30).All(&userList)
	if err != nil {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "查询失败！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
		return
	}
	//查询的条数大于0
	if count > 0 {
		for i := 0; i < len(userList); i++ {
			name:=userList[i].UserName
			fmt.Println("user:"+name)
		}
		c.Data["json"] = &userList
		c.ServeJSON()
	}
}

//新增用户
func (c *UerController)AddUser() {
	fmt.Println("AddUser")
	user:=&models.User{
		UserName: "孙权",
		UserPassword: "123456",
		UserPhone: "15693939393",
		RoleId: 1,
		RegTime: "2022-03-10",
		UserStatus: 1,
	}
	//1 orm对象
	o := orm.NewOrm()

	//2 插入记录
	n,err:=o.Insert(user)

	if err == nil && n > 0 {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "插入成功！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}else{
		res:=&models.ResponseData{
			Code: 0,
			Msg: "插入失败！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}
}

//删除用户
func (c *UerController)DelUser() {
	//获取参数
	id:=c.GetString("id")
	if id==""||id=="null"{
		res:=&models.ResponseData{
			Code: 0,
			Msg: "参数为空！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
		return
	}
	//1 orm对象
	o := orm.NewOrm()

	iId,_:=strconv.ParseInt(id,10,64)
	user:=models.User{
		Id: iId,
	}
	//2 删除记录
	n, err := o.Delete(&user)
	if err == nil && n > 0 {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "删除成功！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}else{
		res:=&models.ResponseData{
			Code: 0,
			Msg: "删除失败！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}
}

//修改用户密码
func (c *UerController)UpdateUser() {
	//获取参数
	id:=c.GetString("id")
	password:=c.GetString("password")
	if id==""||id=="null"|| password==""||password=="null" {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "参数为空！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
		return
	}
	//1 orm对象
	o := orm.NewOrm()

	//2 查询用户
	iId,_:=strconv.ParseInt(id,10,64)
	user:=models.User{
		Id:iId,
	}
	err1:=o.Read(&user)
	if err1 != nil  {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "用户不存在！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
		return
	}

	//3 更新记录
	user.UserPassword= password
	n, err2 := o.Update(&user)
	if err2 == nil && n > 0 {
		res:=&models.ResponseData{
			Code: 0,
			Msg: "更新成功！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}else{
		res:=&models.ResponseData{
			Code: 0,
			Msg: "更新失败！",
		}
		c.Data["json"] = &res
		c.ServeJSON()
	}
}
